package com.beordie.version_2.mvc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description
 * @Date 2022/2/17 11:04
 * @Created 30500
 */
public class BODView {
    private File viewFile;

    public BODView(File file) {
        this.viewFile = file;
    }

    /**
     * 渲染页面
     * @param model 渲染数据
     * @param req
     * @param resp
     * @throws IOException
     */
    public void render(Map<String,?> model, HttpServletRequest req, HttpServletResponse resp) throws IOException {
        StringBuilder builder = new StringBuilder();
        RandomAccessFile accessFile = new RandomAccessFile(this.viewFile, "r");
        String line = null;
        while (null != (line = accessFile.readLine())) {
            line = new String(line.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);

            Pattern pattern = Pattern.compile("!\\{[^\\}]+\\}", Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(line);
            while (matcher.find()) {
                String paramName = matcher.group();
                paramName = paramName.replaceAll("!\\{|\\}", "");
                Object paramValue = model.get(paramName);
                if (paramValue == null) { continue; }
                line = matcher.replaceFirst(paramValue.toString());
                matcher = pattern.matcher(line);
            }
            builder.append(line);
        }
        resp.setCharacterEncoding("utf8");
        resp.getWriter().write(builder.toString());
    }
}
